package cn.wolfcode.trip.base.util;

import com.aliyun.oss.OSSClient;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 文件上传工具
 */
public class UploadUtil {
	//公共的图片区域
	public static final String PATH ="d:/trip";


	//阿里云域名
	public static final String ALI_PATH ="https://wolfcode.oss-cn-hangzhou.aliyuncs.com/";
	/**
	 * 处理文件上传
	 * @param file
	 * @param basePath      
	 * @return  123.png
	 */
	public static String upload(MultipartFile file, String basePath) {
		String uuid = UUID.randomUUID().toString();

		String orgFileName = file.getOriginalFilename();
		String ext= "." + FilenameUtils.getExtension(orgFileName);
		String fileName = uuid + ext;
		try {
			File targetFile = new File(basePath, fileName);
			FileUtils.writeByteArrayToFile(targetFile, file.getBytes());

			return "/upload/" + fileName;

		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 上传图片到阿里云服务器
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static String uploadAliyun(MultipartFile file) throws Exception {
		// Endpoint以杭州为例，其它Region请按实际情况填写。
		String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
		// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
		String accessKeyId = "LTAIjhxx8RVLAg3k";
		String accessKeySecret = "Ysuu9XUHonmGaIixhVFEh8r0C1nuvC";

		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 上传文件流。

		String uuid = UUID.randomUUID().toString();
		String orgFileName = file.getOriginalFilename();
		String ext = "." + FilenameUtils.getExtension(orgFileName);
		String fileName = uuid + ext;
		ossClient.putObject("wolfcode", fileName, file.getInputStream());
		// 关闭OSSClient。
		ossClient.shutdown();
		return fileName;

	}
	
}
























